from django.contrib.auth import login,logout,authenticate
from django.views.decorators.http import require_POST
from .forms import loginForms,RegisterForm
# from django.http import JsonResponse
from utils import restful
from django.shortcuts import redirect,reverse
from utils.captcha.xfzcaptcha import Captcha
from io import BytesIO
from django.http import HttpResponse
from utils import smssender
import json
from django.core.cache import cache
# from .models import User
from django.contrib.auth import get_user_model

User = get_user_model()

@require_POST
def login_view(request):
    # 获取form表单
    form = loginForms(request.POST)
    # 假如验证成功
    if form.is_valid():
        telephone = form.cleaned_data.get("telephone")
        password = form.cleaned_data.get("password")
        remember = form.cleaned_data.get("remember")
        # 授权
        user = authenticate(request,username=telephone,password=password)
        if user:   #授权通过
            if user.is_active:    #已激活
                login(request,user)       #登录
                if remember:
                    # 设置session为默认的两个星期过期
                    request.session.set_expiry(None)
                else:
                    # 设置session为关闭浏览器即过期
                    request.session.set_expiry(0)
                # return JsonResponse({'code':200,'message':'','data':''})
                return restful.ok()
            else:
                # return JsonResponse({'code':401,'message':'您的账号已经被冻结了','data':''})
                return restful.auth_error(message="您的账号已经被冻结了！")
        else:
            # return JsonResponse({'code':400,'message':'手机号码或者密码错误','data':''})
            return restful.params_error(message="手机号码或者密码错误！")
    else:
        errors = form.get_errors()
        # return JsonResponse({"code":400,"message":'','data':errors})
        return restful.params_error(message=errors)

# 退出登录
def logout_view(request):
    logout(request)
    return redirect(reverse('index'))

# 生成图形验证码
def img_captcha(request):
    text,image = Captcha.gene_code()
    # BytesIO相当于一个管道，用来存储图片的流数据
    out = BytesIO()
    # 调用image的save方法，将这个图片保存到BytesIO中
    image.save(out,'png')
    # 将BytesIO的指针移动到最开始的位置
    out.seek(0)
    response = HttpResponse(content_type='image/png')
    # 将BytesIO中的数据读取出来，并保存到response对象上
    response.write(out.read())
    # tell方法可以获取到文件指针的位置
    response['content-length'] = out.tell()
    # 设置缓存
    cache.set(text.lower(), text.lower(), 5*60)
    return response

# 发送手机验证码
def sms_captcha(request):
    # 获取输入的telephone的值
    telephone = request.GET.get('telephone')
    # 调用这个函数生成随机code
    code = Captcha.gene_text()
    # 增加手机验证码的缓存
    cache.set(telephone,code,5*60)
    print('您的短信验证码是：'+code)
    # 发送成功会返回True，失败会返回False
    # result = smssender.send(telephone, code)
    # print(result)
    # if result:
    #     return restful.ok()
    # else:
    #     return restful.params_error(message='短信验证码发送失败！')
    return restful.ok()

def cache_test(request):
    cache.set('username','zhiliao',60)
    result = cache.get('username')
    return HttpResponse("success")

# 注册
@require_POST
def register(request):

    form = RegisterForm(request.POST)

    if form.is_valid():
        telephone = form.cleaned_data.get("telephone")
        username = form.cleaned_data.get('username')
        password = form.cleaned_data.get('password1')
        # 创建新用户并登陆
        user = User.objects.create_user(telephone=telephone,username=username,password=password)
        login(request,user)
        return restful.ok()
    else:
        print(form.get_errors())
        return restful.params_error(message=form.get_errors())